import React, { useEffect, useRef, useCallback, ChangeEvent, useState } from 'react'
import './app.less'
import { isDesktop, getProcessNodeEnv, ipcRendererSend, ipcRendererOn } from '@common/desktopUtils'
import { Button, Tabs } from 'antd'
import TableInfo from '@app/component/tableInfo'
import UploadFile from '@app/component/uploadFile'
import Authorization from '@app/component/authorization'

function App() {
  const openDevtoolInput = useRef<HTMLInputElement>(null)
  const isDevelopment = useRef(getProcessNodeEnv() === 'development')
  const [isAccess, setIsAccess] = useState(false)

  const openDevtool = useCallback(() => {
    ipcRendererSend('mainWindow-open-devtool')
  }, [])
  useEffect(() => {
    // setTimeout(() => {
    //   openDevtool()
    // }, 1000)
    ipcRendererSend('AuthValid')
    ipcRendererOn('is-AuthValid', (_, data) => {
      setIsAccess(data as boolean)
    })

    document.addEventListener('keydown', (e) => {
      const { ctrlKey, metaKey, altKey, key } = e
      // 开发环境使用ctrl + F12打开控制台

      if (isDevelopment.current && ctrlKey && key === 'F12') {
        openDevtool()
      }
      // 开发环境使用ctrl + win + alt + F12，然后键入'open devtool'打开控制台
      if (!isDevelopment.current && ctrlKey && metaKey && altKey && key === 'F12') {
        if (openDevtoolInput.current) {
          openDevtoolInput.current.focus()
        }
      }
    })
  }, [openDevtool])
  const handleExit = () => {
    ipcRendererSend('logout')
  }
  return (
    <div id="electron-app">
      {isAccess && (
        <Button style={{ position: 'absolute', right: 20, top: 8, zIndex: 99 }} onClick={handleExit}>
          退出登录
        </Button>
      )}

      <div className={isDesktop() ? 'desktop-app-content' : 'app-content'}>
        {isAccess ? (
          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: '1',
                label: '肉鸡上传',
                children: <UploadFile />
              },
              {
                key: '2',
                label: '肉鸡智投',
                children: <TableInfo />
              }
            ]}
          />
        ) : (
          <Authorization />
        )}
      </div>
    </div>
  )
}

export default App
